package qqserver.service;

import qqcommon.Message;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author DCSGO
 * @version 1.0
 * 该类用于将用户离线时接收到的消息
 * 在用户上线时将其发送
 */
public class SendMessageToOfflineService {
    private static final ConcurrentHashMap<String, ArrayList<Message>> userMessages = new ConcurrentHashMap<>();
    private static final HashSet<String> offlineUsers = new HashSet<>();

    public static void sendMessages(String id, Socket clientSocket) {
        if (id == null || clientSocket == null) {
            return;
        }
        if (isOfflineUser(id) && hasMessage(id)) {
            try {
                ArrayList<Message> messages = getMessages(id);
                for (Message m : messages) {
                    //客户端每次接收都 new 一个 ObjectInputStream 为与之匹配 我们也必须要
                    //每写一个 message 就 new 一个 ObjectOutputStream 具体原因可查看
                    //https://blog.csdn.net/weixin_44142151/article/details/124188691
                    ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());
                    oos.writeObject(m);
                }
                messages.clear();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void addOfflineUser(String id) {
        offlineUsers.add(id);
        userMessages.put(id, new ArrayList<>());
    }

    public static void removeOfflineUser(String id) {
        offlineUsers.remove(id);
    }

    public static boolean isOfflineUser(String id) {
        return offlineUsers.contains(id);
    }

    public static boolean hasMessage(String id) {
        return !userMessages.get(id).isEmpty();
    }

    public static void addMessage(Message message) {
        ArrayList<Message> messages = userMessages.get(message.getReceiver());
        messages.add(message);
    }

    public static ArrayList<Message> getMessages(String id) {
        return userMessages.get(id);
    }
}
